package com.it00zyq.admin.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it00zyq.common.entity.User;
import com.it00zyq.common.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author zyq
 * @Date 2022/4/25 10:49
 * @Description TODO
 * @Version 1.0
 **/
@Component
@RequiredArgsConstructor
public class MyUserDetailService implements UserDetailsService {
    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        MyUserDetails myUserDetails = new MyUserDetails();
        if(ObjectUtils.isNotEmpty(user)) {
            Set<GrantedAuthority> authoritiesSet = new HashSet<>();
            authoritiesSet.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));
            myUserDetails.setAuthorities(authoritiesSet);
        }
        return myUserDetails;
    }
}
